﻿//-----------------------------------------------------------------------
// <copyright file="ToolModule.cs" company="Nathan Miller">
// Copyright (c) Nathan Miller.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
namespace App.Modules.Tool
{
    using System.Collections.Generic;
    using App.Exceptions;
    using App.Modules.Component;
    using App.Modules.Message;
    using App.Modules.Package;
    using TileTool.Editor.Tool.Scene;
    using TileTool.Log;
    using TileTool.Tool;

    /// <summary>
    /// Application tool module.
    /// </summary>
    public class ToolModule : Module
    {
        #region Constants - Private

        /// <summary>
        /// Log message group.
        /// </summary>
        private const string LogGroup = "ToolModule";

        #endregion

        #region Fields - Private

        /// <summary>
        /// List of scene tools that are currently installed.
        /// </summary>
        private IList<ISceneTool> sceneToolList = new List<ISceneTool>();

        #endregion

        #region Properties - Public

        /// <summary>
        /// Gets the tool manager for the application.
        /// </summary>
        public IToolManager ToolManager
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the list of scene tools with the most recently installed tool
        /// last in the lsit.
        /// </summary>
        public IList<ISceneTool> SceneTools
        {
            get
            {
                return this.sceneToolList;
            }
        }

        #endregion

        #region Methods - Public

        /// <summary>
        /// Called when the application is starting up.
        /// </summary>
        public override void Startup()
        {
            LogSystem.LogStartup(LogGroup, "Starting...");

            ComponentModule componentModule = GetModule<ComponentModule>();
            MessageModule messageModule = GetModule<MessageModule>();
            ToolManagerFactoryComponentBase factory = componentModule.Get<ToolManagerFactoryComponentBase>(ComponentAliases.ToolManager);

            LogSystem.LogStartup(LogGroup, "Allocating tool manager...");

            ToolManagerCreateData createData = new ToolManagerCreateData();
            createData.MessageRouter = messageModule.MessageRouter;

            this.ToolManager = factory.Allocate(createData);

            this.ToolManager.Installed += this.HandleToolInstall;
            this.ToolManager.Uninstalled += this.HandleToolUninstall;

            base.Startup();
        }

        /// <summary>
        /// Called when the application is shutting down.
        /// </summary>
        public override void Shutdown()
        {
            base.Shutdown();

            this.ToolManager = null;
        }

        /// <summary>
        /// Install all default tools.
        /// </summary>
        public void InstallDefaultTools()
        {
            ComponentModule componentModule = GetModule<ComponentModule>();
            PackageModule packageModule = GetModule<PackageModule>();
            PackageData data = packageModule.Data;

            foreach (string toolName in data.StartupToolNames)
            {
                ToolFactoryComponentBase factory = componentModule.Get<ToolFactoryComponentBase>(toolName);
                ITool tool = factory.Allocate();

                this.ToolManager.Install(tool);
            }
        }

        /// <summary>
        /// Install the tool with the passed component alias.
        /// </summary>
        /// <param name="toolComponentAlias">Tool component alias to install.</param>
        public void InstallTool(string toolComponentAlias)
        {
            try
            {
                ComponentModule componentModule = GetModule<ComponentModule>();
                ToolFactoryComponentBase factory = componentModule.Get<ToolFactoryComponentBase>(toolComponentAlias);
                ITool tool = factory.Allocate();

                this.ToolManager.Install(tool);
            }
            catch (AppException e)
            {
                LogSystem.LogError(LogGroup, "Failed to install tool with component alias: " + toolComponentAlias);
                LogSystem.LogError(LogGroup, "Error: " + e.ToString());
            }
        }

        #endregion

        #region Methods - Private

        /// <summary>
        /// Handle a tool install.
        /// </summary>
        /// <param name="tool">Tool that was isntalled.</param>
        private void HandleToolInstall(ITool tool)
        {
            ISceneTool sceneTool = tool as ISceneTool;
            if (sceneTool == null)
            {
                return;
            }

            this.sceneToolList.Add(sceneTool);
        }

        /// <summary>
        /// Handle a tool uninstall.
        /// </summary>
        /// <param name="tool">Tool that was uninstalled.</param>
        private void HandleToolUninstall(ITool tool)
        {
            ISceneTool sceneTool = tool as ISceneTool;
            if (sceneTool == null)
            {
                return;
            }

            this.sceneToolList.Remove(sceneTool);
        }

        #endregion
    }
}
